package cn.cjx.system.service.impl;


import cn.cjx.system.domain.Role;
import cn.cjx.system.mapper.RoleMapper;
import cn.cjx.system.service.IRoleService;
import cn.cjx.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cjx
 * @since 2022-05-13
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
	@Autowired
	private RoleMapper roleMapper;

	@Override
	public void save(Role role) {

		roleMapper.save(role);

		initRelationTable(role);

	}

	private void initRelationTable(Role role) {
		Long roleId = role.getId();
		List<Long> menus = role.getMenus();
		List<Long> permissions = role.getPermissions();
		//1.删除历史数据,如果有，就先删除原来的，如果没有就直接新增
		if (roleId != null) {
			roleMapper.removeRoleMenuByRoleId(roleId);
			roleMapper.removeRolePermissionByRoleId(roleId);
		}
		//2.保存菜单数据
		if (menus != null) {
			HashMap<String, Object> hashMap = new HashMap<>();
			hashMap.put("roleId",roleId);
			hashMap.put("menus",menus);
			roleMapper.saveRoleMenu(hashMap);
		}
		//保存权限
		if (permissions != null) {
			HashMap<String, Object> map = new HashMap<>();
			map.put("roleId",roleId);
			map.put("permissions",permissions);
			roleMapper.saveRolePermission(map);
		}


	}


}
